package naga.x.platform2.channel.qunhei.support;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import naga.x.platform2.App;
import naga.x.platform2.app.Channel;
import naga.x.platform2.utils.NumberUtils;
import naga.x.platform2.utils.StringUtils;

@Configuration
@EnableAutoConfiguration
@ConfigurationProperties(locations = "classpath:qunhei.properties")
public class QunHeiConfig implements InitializingBean {

	private String gameId;
	private String loginKey;
	private String payKey;
	private String clientUrl;
	private String goods; // 商品表(productId1=goodsId1,productId2=goodsId2,...)
	private Map<Integer, Integer> goodsMap;
	private boolean debug;

	public String getGameId() {
		return gameId;
	}

	public void setGameId(String gameId) {
		this.gameId = gameId;
	}
	
	public String getLoginKey() {
		return loginKey;
	}

	public void setLoginKey(String loginKey) {
		this.loginKey = loginKey;
	}

	public String getPayKey() {
		return payKey;
	}

	public void setPayKey(String payKey) {
		this.payKey = payKey;
	}

	public String getClientUrl() {
		return clientUrl;
	}

	public void setClientUrl(String clientUrl) {
		this.clientUrl = clientUrl;
	}

	public String getGoods() {
		return goods;
	}

	public void setGoods(String goods) {
		this.goods = goods;
	}
	
	public boolean isDebug() {
		return debug;
	}

	public void setDebug(boolean debug) {
		this.debug = debug;
	}

	public Integer getGoodsId(Integer productId) {
		return goodsMap.get(productId);
	}
	
	@Override
	public String toString() {
		return "[gameId=" + gameId + ", loginKey=" + loginKey + ", payKey=" + payKey + ", clientUrl="
				+ clientUrl + ", goodsMap=" + goodsMap + ", debug=" + debug + "]";
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		parseGoods();
		Channel.QUNHEI.debug = debug;
		App.LOG.info("[QUNHEI CONFIG LOADED]{}", this);
	}
	
	private void parseGoods() {
		if (StringUtils.isEmpty(goods)) {
			goodsMap = Collections.emptyMap();
			return;
		}
		goodsMap = new LinkedHashMap<>();
		String[] strs = StringUtils.split(goods, ",");
		for (String str : strs) {
			int n = str.indexOf('=');
			int productId = NumberUtils.parseInt(StringUtils.trim(str.substring(0, n)));
			int goodsId = NumberUtils.parseInt(StringUtils.trim(str.substring(n + 1)));
			goodsMap.put(productId, goodsId);
		}
	}
	
	
}
